package session;

import java.util.List;

import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.persistence.Query;

import entity.Appointment;
import entity.Players;
import entity.User;

@Stateless
@Remote(PlayersDao.class)
public class PlayersDaoBean extends GenericDaoBean<Players, Integer>  implements PlayersDao{

	@SuppressWarnings("unchecked")
	@Override
	public List<Players> findAllByAppointment(Appointment appointment) {
		try{
			Query q = em.createQuery("SELECT p FROM Players p WHERE p.appointment=:app AND p.appointment.deleted=false AND p.participated=true ORDER BY p.user.firstName ASC,p.user.lastName ASC");
			q.setParameter("app", appointment);
			return q.getResultList();
		}catch(Exception e){
			return null;
		}
	}

	@Override
	public Players findPlayerByAppointment(User user,Appointment appointment) {
		try{
			Query q = em.createQuery("SELECT p FROM Players p WHERE p.appointment=:app AND p.appointment.deleted=false AND p.participated=true AND p.user=:usr ORDER BY p.user.firstName ASC,p.user.lastName ASC");
			q.setParameter("app", appointment);
			q.setParameter("usr", user);
			return (Players)q.getSingleResult();
		}catch(Exception e){
			return null;
		}
	}
	
	@Override
	public Integer sumGoals(Appointment appointment, char team) {
		try{
			Query q = em.createQuery("SELECT SUM(p.goal) FROM Players p WHERE p.appointment=:app AND p.team=:tea AND p.participated=true");
			q.setParameter("app", appointment);
			q.setParameter("tea", team);
			return ((Long) q.getSingleResult()).intValue();
		}catch(Exception e){
			return null;
		}
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Players> findMvpByAppointment(Appointment appointment) {
		try{
			Query q = em.createQuery("SELECT p FROM Players p WHERE p.appointment=:app AND p.participated=true ORDER BY p.mvp DESC, p.goal DESC");
			q.setParameter("app", appointment);
			return q.getResultList();
		}catch(Exception e){
			return null;
		}
	}
	

}
